package com.audaque.springboot.foshanupload.web.datamongodbdemo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.web.datamongodbdemo.api.MusicControllerApi;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.Book;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.Chapter;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.MusicDetail;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.Person;
import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.qo.MusicQo;
import com.mongodb.client.result.DeleteResult;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * @author zgb
 * @desc 要求使用ObjectId
 * @date 2023-08-15 19:49:54
 */
@RestController
@RequestMapping("/musicDetailMongoTemplate")
public class MusicDetailMongoTemplateController implements MusicControllerApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * s：直接面向Model
     * @param musicDetail
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/add")
    public String add(@RequestBody MusicDetail musicDetail) {
        musicDetail.setId(null);
        MusicDetail insert = mongoTemplate.insert(musicDetail);
        String id = insert.getId();
        return id;
    }



    @Override
    @PutMapping("/override")
    public void override(MusicDetail musicDetail) {
        mongoTemplate.save(musicDetail);
    }


    @Override
    @GetMapping("/get/{id}")
    public MusicDetail get(@PathVariable("id") String id) {
        System.out.println("helloword2");
        return mongoTemplate.findById(id, MusicDetail.class);
    }

    @Override
    @DeleteMapping("/del/{id}")
    public void del(@PathVariable("id") String id) {
        DeleteResult id1 = mongoTemplate.remove(new Query().addCriteria(Criteria.where("_id").is(id)), MusicDetail.class);
        long deletedCount = id1.getDeletedCount();

    }

    @Override
    public Page<MusicDetail> page(int page, int size, MusicQo musicQo) {
        return null;
    }

    @GetMapping("/dBRef")
    public MusicDetail dBRef(@RequestParam("id") String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, MusicDetail.class);
    }


    @GetMapping("/dBRef2")
    public MusicDetail dBRef2(@RequestParam("bookId") String bookId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("book._id").is(bookId));
        return mongoTemplate.findOne(query, MusicDetail.class);
    }


    @GetMapping("/dBRef3")
    public MusicDetail dBRef3(@RequestParam("chapterId") String chapterId) {
        Query query = new Query();
        //chapter条件查不到是因为主文档里没有chapter字段
        query.addCriteria(Criteria.where("book.chapter._id").is(chapterId));
        return mongoTemplate.findOne(query, MusicDetail.class);
    }
    /**
     * e：直接面向Model
     * @param musicDetail
     * @return
     */


    @Override
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/edit")
    public void edit(@RequestBody MusicDetail musicDetail) throws Exception {
        String id = musicDetail.getId();
        if (StringUtils.isBlank(id)) {
            throw new Exception("id不能为null");
        }

        MusicDetail byId = mongoTemplate.findById(id, MusicDetail.class);
        if (byId==null) {
            throw new Exception("根据id查不到该记录");
        }

        CopyOptions copyOptions = CopyOptions.create();
        copyOptions.setIgnoreNullValue(true);
        copyOptions.setIgnoreProperties("book");
        BeanUtil.copyProperties(musicDetail,byId,copyOptions);

        Book book = musicDetail.getBook();
        Book book1 = byId.getBook();
        copyOptions.setIgnoreProperties("chapter");
        BeanUtil.copyProperties(book,book1,copyOptions);

        Chapter chapter = book.getChapter();
        Chapter chapter1 = book1.getChapter();
        BeanUtil.copyProperties(chapter,chapter1,copyOptions);
        book1.setChapter(chapter1);
        byId.setBook(book1);



        JSONConfig jsonConfig = JSONConfig.create();
        jsonConfig.setIgnoreNullValue(true);
        jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = JSONUtil.toJsonStr(byId,jsonConfig);
        Document document = Document.parse(s);


        //覆盖
        Update update = Update.fromDocument(document);
        mongoTemplate.updateFirst(new Query().addCriteria(Criteria.where("id").is(id)), update, MusicDetail.class);


    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/editField")
    public void editField(String id, String name) throws Exception {
        //更新条件
        Query query = new Query(Criteria.where("id").is(id));

        //更新值
        Update update = new Update().set("musicName", name);
        //更新查询满足条件的文档数据（第一条）
        mongoTemplate.updateFirst(query, update, Person.class);
    }

    /**
     * s：面向Document:bean>json>document
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/override2json")
    public void override2json(@RequestParam String id) throws Exception {
        MusicDetail byId = mongoTemplate.findById(id, MusicDetail.class);
        if (byId==null) {
            throw new Exception("根据id查不到该记录");
        }

        JSONConfig jsonConfig = JSONConfig.create();
        jsonConfig.setIgnoreNullValue(true);
        jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = JSONUtil.toJsonStr(byId,jsonConfig);
        Document document = Document.parse(s);


        //覆盖
        Update update = Update.fromDocument(document);
        mongoTemplate.updateFirst(new Query().addCriteria(Criteria.where("id").is(id)), update, MusicDetail.class);

    }
    /**
     * e：面向Document:bean>json>document
     */

}
